'use strict';
const moment = require('moment');
const conn = require('../../../server/libs/DB/meter/asycnPool').pool;
const _ = require('underscore');

//const log = require('../../server/libs/SysLog/Write').log;

function flowMonthCalculation(date) {
    let taskDate = date ? moment(date) : moment();
    let currentDate = taskDate.subtract(1, 'month').format('YYYY-MM');
    let lastDate = taskDate.subtract(1, 'month').format('YYYY-MM');
    conn.query(`SELECT * FROM device_region_file;`, function (err, deviceList) {
        if (!err) {
            let stationGroup = _.groupBy(deviceList, 'station_id');
            _.forEach(stationGroup, function (stationDeviceList, key) {
                let flowDataTable = `flow_day_${key}`;
                let sql = ` SELECT 
                          rd_e.device_no,
                          rd_e.total_cumflow,
                          DATE_FORMAT(
                            rd_e.total_cumflow_time,
                            '%Y-%m-%d %H:%i:%s'
                          ) total_cumflow_time,
                          DATE_FORMAT(rd_e.data_date, '%Y-%m-%d') data_date 
                        FROM
                          ${flowDataTable} rd_e 
                          RIGHT JOIN 
                            (SELECT 
                              MAX(fd.data_date) data_date,
                              fd.device_no 
                            FROM
                              device_region_file drf 
                              LEFT JOIN ${flowDataTable} fd 
                                ON fd.device_no = drf.device_union 
                                AND DATE_FORMAT(fd.data_date, '%Y-%m') = ?
                            WHERE fd.total_cumflow IS NOT NULL 
                            GROUP BY fd.device_no) rd_d 
                            ON rd_d.data_date = rd_e.data_date 
                            AND rd_d.device_no = rd_e.device_no;
             SELECT 
                          rd_e.device_no,
                          rd_e.total_cumflow,
                          DATE_FORMAT(
                            rd_e.total_cumflow_time,
                            '%Y-%m-%d %H:%i:%s'
                          ) total_cumflow_time,
                          DATE_FORMAT(rd_e.data_date, '%Y-%m-%d') data_date 
                        FROM
                          ${flowDataTable} rd_e 
                          RIGHT JOIN 
                            (SELECT 
                              MAX(fd.data_date) data_date,
                              fd.device_no 
                            FROM
                              device_region_file drf 
                              LEFT JOIN ${flowDataTable} fd 
                                ON fd.device_no = drf.device_union 
                                AND DATE_FORMAT(fd.data_date, '%Y-%m') = ? 
                            WHERE fd.total_cumflow IS NOT NULL 
                            GROUP BY fd.device_no) rd_d 
                            ON rd_d.data_date = rd_e.data_date 
                            AND rd_d.device_no = rd_e.device_no;`;
                conn.query(sql, [currentDate, lastDate], function (err, queryList) {
                    let insertDataList = [];
                    if (!err) {
                        let currentDataList = queryList[0];//获取当月数据
                        let lastDataList = queryList[1];
                        _.forEach(currentDataList, function (currentData) {
                            let matchLastData;
                            let matchLastDataList = _.filter(lastDataList, {device_no: currentData.device_no});
                            if (matchLastDataList.length) matchLastData = matchLastDataList.shift();
                            if (matchLastData && matchLastData.total_cumflow && currentData.total_cumflow) {
                                let monthCumflow = currentData.total_cumflow - matchLastData.total_cumflow;
                                let monthDataInsertObj = {
                                    device_no: currentData.device_no,
                                    data_date: currentDate + '-01',
                                    month_cumflow: monthCumflow,
                                    begin_total_cumflow_time: matchLastData.total_cumflow_time,
                                    begin_total_cumflow: matchLastData.total_cumflow,
                                    end_total_cumflow_time: currentData.total_cumflow_time,
                                    end_total_cumflow: currentData.total_cumflow,
                                };
                                    let insertSql = `INSERT INTO flow_month SET ? ON DUPLICATE KEY UPDATE ?`;
                                    conn.query(insertSql, [monthDataInsertObj, monthDataInsertObj], function (err) {
                                        if (err) console.log(err);
                                    });
                                //insertDataList.push(monthDataInsertObj);
                            }
                        });
                        console.log(insertDataList);
                    }
                });
            });


        } else {
            console.log(err)
        }
    });

}

module.exports = flowMonthCalculation;